package com.wz.netty.transport;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TransportClient {
	private Logger log = LoggerFactory.getLogger(TransportClient.class);

	private EventLoopGroup workerGroup;

	public boolean connect(String ip, int port){
		Bootstrap bootstrap = new Bootstrap();
		workerGroup  = new NioEventLoopGroup();
		bootstrap.group(workerGroup);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
		bootstrap.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new TransportClientHandler());
			}
		});
		try {
			ChannelFuture channelFuture = bootstrap.connect(ip, port);
			return channelFuture.sync().isSuccess();
		} catch (Exception e) {
			log.error("连接远程异常", e);
			workerGroup.shutdownGracefully();
			return false;
		}
	}

	public void close(){
		workerGroup.shutdownGracefully();
	}

	public static void main(String[] args) {
		new TransportClient().connect("127.0.0.1", 9981);
	}
}